package com.ruoyi.company.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyAddress;
import com.ruoyi.company.domain.CompanyAudit;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.mapper.CompanyOtherMapper;
import com.ruoyi.company.service.ICompanyServer;
import com.ruoyi.company.utils.pdf.HtmlToPdf;
import com.ruoyi.company.utils.pdf.ImgToPdf;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductAll;
import com.ruoyi.product.mapper.AICodeMapper;
import com.ruoyi.product.mapper.ProductMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.warehousing.mapper.WarehousingMapper;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.*;


/**
 * @author WangChangShuo
 * @date 2022/4/13 8:49
 */
@Service
public class CompanyServerImpl implements ICompanyServer {

    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    CompanyOtherMapper companyOtherMapper;

    @Autowired
    SysDeptMapper sysDeptMapper;

    @Autowired
    WarehousingMapper warehousingMapper;

    @Autowired
    AICodeMapper aiCodeMapper;

    public static void main(String[] args) {
        String time = "2024-01-19T16:00";
        System.out.println(time.substring(0, 10));
    }

    /**
     * 新增 合作单位表
     *
     * @param company 合作单位信息
     * @return 新增的条数
     */
    @Override
    @Transactional
    public int insertCompany(Company company) {
        return companyMapper.insertCompany(company);
    }

    /**
     * 根据主键查询信息
     *
     * @param companyId 主键
     * @return 结果
     */
    @Override
    public Company selectByCompanyId(Long companyId) {
        return companyMapper.selectByCompanyId(companyId);
    }

    @Override
    public void importCompany(InputStream inputStream) throws IOException {
        Product product = new Product();
        try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream);) {
            XSSFSheet sheet = workbook.getSheetAt(0); //Excel第一个页签
            int totalIndex = sheet.getLastRowNum();
            for (int rowIndex = 1; rowIndex <= totalIndex; rowIndex++) {
                XSSFRow row = sheet.getRow(rowIndex);
                if (row != null) {
                    for (int i = 0; i <= 10; i++) {
                        if (row.getCell(i) != null) {
                            row.getCell(i).setCellType(CellType.STRING);

                        } else {
                            row.createCell(i).setCellType(CellType.STRING);

                        }
                    }
                    if (row.getCell(0) != null) {
                        product.setMedicalNumber(row.getCell(0).getStringCellValue());
                        product.setProductProofName(row.getCell(1).getStringCellValue());
                        product.setProductProofAddress(row.getCell(2).getStringCellValue());
                        productMapper.updateproductProofName(product);

                    }

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateCompanyAddress(List<CompanyAddress> companyAddressList, Long companyId) {
        Long id;
        CompanyAddress companyAddress = new CompanyAddress();
        List<Long> companyAddressList1 = new ArrayList<>();
        List<CompanyAddress> list = companyMapper.selectCompanyAddressById(companyId);
        if (companyAddressList.size() != 0) {
            for (CompanyAddress companyAddress1 : companyAddressList) {
                companyAddress.setId(companyAddress1.getId());
                companyAddress1.setCompanyId(companyId);
            }
            ArrayList<Long> arrayList = new ArrayList();
            try {
                if (companyAddressList.size() != 0) {
                    for (CompanyAddress value : list) {
                        arrayList.add(value.getId());
                    }
                    for (CompanyAddress companyAddress1 : companyAddressList) {
                        id = companyAddress1.getId();
                        if (companyMapper.selectCompanyAddressId(companyAddress1) == 1) {
                            companyAddressList1.add(id);
                            companyMapper.updateCompanyAddress(companyAddress1);
                        } else {
                            companyMapper.insertComPanyAddress(companyAddress1);
                        }
                        TreeSet<Long> longs = new TreeSet<>();
                        boolean b = arrayList.removeAll(companyAddressList1);
                        for (Long along : arrayList) {
                            longs.add(along);
                        }
                        //修改数组中剩下的产品
                        if (longs.size() != 0) {
                            for (Long aLong : longs) {
                                companyMapper.deleteCompanyAddress(aLong);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            for (CompanyAddress value : list) {
                companyMapper.deleteCompanyAddress(value.getId());
            }
        }
    }

    @Override
    public List<CompanyAddress> selectCompanyAddress(Long companyId) {
        return companyMapper.selectCompanyAddress(companyId);
    }

    /**
     * 修改合作单位信息
     *
     * @param company 修改的信息
     * @return 结果
     */
    @Override
    public int updateCompany(Company company) {
        return companyMapper.updateCompany(company);
    }

    @Override
    public int updateProduct(ProductAll productAll) {
        Long selectId;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<Product> productList = new ArrayList<>();
        for (Product product : productAll.getProducts()) {
            product.setSelectId(product.getSelectId());
            product.setDeptId(productAll.getCompanyId());
            productList = productMapper.selectProducSqtList(product);
        }

        ArrayList<Long> arrayList = new ArrayList();
        ArrayList<Long> productsList = new ArrayList();
        try {
            if (productAll.getProducts().size() != 0) {
                for (Product product : productList) {
                    arrayList.add(product.getSelectId());
                }

                for (Product product2 : productAll.getProducts()) {
                    product2.setProductId(product2.getProductId());
                    selectId = product2.getSelectId();
                    if (productMapper.selectProductSelectId(product2) == 1) {
                        productsList.add(selectId);
                        product2.setUpdateBy(sysUser.getUserName());
                        product2.setIsAudit("1");
                        productMapper.updateSqProduct(product2);

                    } else if (product2.getSelectId() == 0) {
                        product2.setDeptId(sysUser.getDeptId());
                        product2.setCompanyId(productAll.getCompanyId());
                        product2.setUpdateBy(sysUser.getUserName());
                        productMapper.insertProductSqId(product2);
                    }
                }

                TreeSet<Long> longs = new TreeSet<>();
                boolean b = arrayList.removeAll(productsList);
                for (Long along : arrayList) {
                    longs.add(along);
                }
                //删除数组
                if (longs.size() != 0) {
                    for (Long aLong : longs) {
                        productMapper.updateSqid(aLong);
                    }
                }
            } else {
                productMapper.updateId0(productAll.getCompanyId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Company> mycompany(Long companyId) {
        return companyMapper.mycompany(companyId);
    }

    @Override
    public void CoAuthorization(CompanyAudit companyAudit) {
        String time = "";
        if (companyAudit.getWrtiteTime() != null) {
            time = companyAudit.getWrtiteTime().substring(0, 10);
        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        companyAudit.setAuditcompanyId(sysUser.getDeptId());
        CompanyOther companyOther = new CompanyOther();
        companyOther.setDeptId(sysUser.getDeptId());
        companyOther.setCompanyId(companyAudit.getCompanyId());
        companyOther = companyOtherMapper.selectOther(companyOther);
        Company company = companyMapper.selectCompany(companyAudit.getCompanyId());
        Company gfcompany = companyMapper.selectCompany(sysUser.getDeptId());
        String fileName = company.getCompanyName() + "法人授权委托书" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();

        File d = new File(downloadPath);
        if (!d.exists()) {
            d.mkdir();
        }

        File file = new File(downloadPath + "/CoAuthorization");
        if (!file.exists()) {
            file.mkdir();
        }

        String destPath = downloadPath + "CoAuthorization/" + fileName;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        StringBuilder str = new StringBuilder();
        str.append("<!DOCTYPE html>");
        str.append("<html lang=\"zh\">");
        str.append("<head>\n" +
                "    <meta charset=\"UTF-8\" />\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n" +
                "    <title>Document</title>\n" +
                "  </head>\n" +
                "  <body style=\"font-size: 16px;font-family:SimSun;\">");

        str.append("<p style=\"font-size: 22px; font-weight: bold; text-align: center\">\n" +
                "      法人授权委托书\n" +
                "    </p>\n" +
                "    <p style=\"font-size: 16px; line-height: 1.5; text-indent: 32px\">\n" +
                "      兹由 " + gfcompany.getCompanyName() +
                "      法人代表" + gfcompany.getCorporateRepresentative() + "授权" + companyOther.getUserName() + "先生" + "（身份证号：" + companyOther.getIdcard() + "）" +
                "联系电话:" + companyOther.getPhone() + "邮箱:" + companyOther.getEmail() + "负责我司与" + company.getCompanyName() + "一切销售业务事宜。具体授权如下：\n" +
                "    </p>\n" +
                "    <p style=\"text-indent: 32px; line-height: 2; font-size: 16px\">\n" +
                "      1.授权销售品种:" + companyAudit.getAccreditVariety() +
                "    </p>\n" +
                "    <p style=\"text-indent: 32px; line-height: 2; font-size: 16px\">\n" +
                "      2.授权销售地域：\n" + companyAudit.getAccreditRegional() +
                "    </p>\n" +
                "    <p style=\"text-indent: 32px; line-height: 2; font-size: 16px\">\n" +
                "      3. 授权期限： \n" + companyAudit.getAccreditTime() +
                "    </p>");
        str.append("<div\n" +
                "      style=\"\n" +
                "        line-height: 2;\n" +
                "        font-size: 16;\n" +
                "        position: relative;\n" +
                "        width: 40%;\n" +
                "        float: right;\n" +
                "      \"\n" +
                "    >\n" +
                "      <p style=\"\">" + gfcompany.getCompanyName() + "</p>\n" +
                "      <p style=\"\">授权人（签章）：</p>\n" +
                "      <p style=\"\">" + time + "</p>\n" +
                "    </div>\n" +
                "  </body>\n" +
                "</html>");

        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());

        String downloadPath1 = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath1);
        if (!file1.exists()) {
            file1.mkdir();
        }

        String uploadPath = RuoYiConfig.getUploadPath();
        String purUrl = "";

        int sbsoluteY = 435;
        String purImgPath = "";

        String fileStr = downloadPath1 + "CoAuthorization/" + fileName;
        String fileStr2 = downloadPath1 + "CoAuthorization/" + gfcompany.getCompanyName() + "授权" + fileName;

        purUrl = gfcompany.getElectronicSealUrl();
        String zmphoto = companyOther.getIdcardzmPhoto();
        String fmphoto = companyOther.getIdcardfmPhoto();
        String[] split1 = purUrl.split("/profile/upload");
        String[] split2 = zmphoto.split("/profile/upload");
        String[] split3 = fmphoto.split("/profile/upload");
        purImgPath = uploadPath + split1[1];

        String zmphoto1 = uploadPath + split2[1];
        String fmphoto1 = uploadPath + split3[1];
        try {

            ImgToPdf.imgAuthorizationPdfRight(fileStr, fileStr2, purImgPath, zmphoto1, fmphoto1, sbsoluteY);
            companyAudit.setLegal("/CoAuthorization/" + gfcompany.getCompanyName() + "授权" + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        insertLegal(companyAudit);
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void SaleAudit(CompanyAudit companyAudit) {
        String time = "";
        if (companyAudit.getWrtiteTime() != null) {
            time = companyAudit.getWrtiteTime().substring(0, 10);
        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        companyAudit.setAuditcompanyId(sysUser.getDeptId());

        Company company = companyMapper.selectCompany(companyAudit.getCompanyId());
        Company gfcompany = companyMapper.selectCompany(sysUser.getDeptId());
        String fileName = company.getCompanyName() + "销售授权书" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();

        File d = new File(downloadPath);
        if (!d.exists()) {
            d.mkdir();
        }

        File file = new File(downloadPath + "/SaleAudit");
        if (!file.exists()) {
            file.mkdir();
        }

        String destPath = downloadPath + "SaleAudit/" + fileName;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int year = LocalDate.now().getYear();
        StringBuilder str = new StringBuilder();
        str.append("<!DOCTYPE html>");
        str.append("<html lang=\"zh\">");
        str.append("<head>\n" +
                "    <meta charset=\"UTF-8\" />\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n" +
                "    <title>医疗器械产品销售授权书</title>\n" +
                "  </head>\n" +
                "  <body style=\"font-size: 16px;font-family:SimSun; line-height: 24px\">");
        str.append("<div style=\"font-size: 16px; line-height: 2.5\">\n" +
                "<div style=\"font-size: 24px; font-weight: bold; text-align: center;\">医疗器械产品销售授权书</div>\n" +
                "<div style=\"text-indent: 2em\">授权编号："+ companyAudit.getSqbh() + "</div>\n" +
                "<div style=\"text-indent: 2em\">授权日期："+companyAudit.getWrtiteTime()+"</div>\n" +
                "<div style=\"text-indent: 2em\">致："+ companyAudit.getClientName() +"</div>\n" +
                "<div style=\"text-indent: 2em\">"+ gfcompany.getCompanyName() +"授权 " + company.getCompanyName() + " 为我司经销商，负责我司产品 " + companyAudit.getProductName() +" 在贵单位的销售及招投标公司，并全权处理相关事宜。</div>\n" +
                "<div style=\"text-indent: 2em\">授权期限："+ companyAudit.getSqqxStart() + " 至 " + companyAudit.getSqqxEnd() +"</div>\n" +
                "<div style=\"text-indent: 2em\">在授权期限内上述经销关系发生任何变更，本公司将给予相应书面通知。自授 权之日起三个月内，若 "+ company.getCompanyName() + " 与本公司没有业务往来，本授权自动作废。</div>\n" +
                "<div style=\"text-align: right\">"+ gfcompany.getCompanyName() + "</div>\n" +
                "<div style=\"text-align: right\">授权日期："+ companyAudit.getWrtiteTime() +"</div>\n" +
                "</div>\n");
        str.append("</body>\n" +
                "</html>");
        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());
        String downloadPath1 = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath1);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String uploadPath = RuoYiConfig.getUploadPath();

        int sbsoluteY = 360;
        String purImgPath = "";

        String fileStr = downloadPath1 + "SaleAudit/" + fileName;
        String fileStr2 = downloadPath1 + "SaleAudit/" + gfcompany.getCompanyName() + "授权" + fileName;
        if (gfcompany.getElectronicSealUrl() != null) {
            String purUrl = gfcompany.getElectronicSealUrl();
            String[] split1 = purUrl.split("/profile/upload");
            purImgPath = uploadPath + split1[1];

            try {
                ImgToPdf.imgToPdfRightSave(fileStr, fileStr2, purImgPath, sbsoluteY);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            companyAudit.setSaleAudit("/SaleAudit/" + gfcompany.getCompanyName() + "授权" + fileName);
            insertsaleAudit(companyAudit);

        }
    }

    @Override
    public Map<String, Object> selectQualification(Long companyId, String type) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        CompanyOther companyOther = new CompanyOther();
        companyOther.setCompanyId(companyId);
        companyOther.setDeptId(sysUser.getDeptId());
        Map<String, Object> resMap = new HashMap<>();
        Company company = companyMapper.selectCompany(companyId);
        Company gfcompany = companyMapper.selectCompany(sysUser.getDeptId());
        companyOther = companyOtherMapper.selectOther(companyOther);

        if (type.equals("0")) {
            String a = "<div>\n" +
                    "    <p style='font-size: 22px; font-weight: bold; text-align: center'>\n" +
                    "      质量保证和售后服务协议\n" +
                    "    </p>\n" +
                    "    <p style='line-height: 1; font-size: 16px'>\n" +
                    "      甲方（供货方）：<span style='text-decoration: underline'\n" +
                    "   >" + gfcompany.getCompanyName() + "</span\n" +
                    "      >\n" +
                    "    </p>\n" +
                    "    <p style='line-height: 1; font-size: 16px'>\n" +
                    "      乙方（购货方）:<span style='text-decoration: underline'\n" +
                    "        >" + company.getCompanyName() + "</span\n" +
                    "      >\n" +
                    "    </p>\n" +
                    "    <p style='font-size: 16px; line-height: 1; text-indent: 32px'>\n" +
                    "      为了严格执行《医疗器械监督管理条例》及国家有关法律、法规的要求，加强医疗器械质量管理，确保医疗器械质量，明确双方质量责任，签订以下质量保证协议：\n" +
                    "    </p>\n" +
                    "    <div style='font-size: 16px; line-height: 1'>\n" +
                    "      <p>一、双方质量责任</p>\n" +
                    "      <p>（1）甲方质量责任</p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        甲方应遵守国家有关医疗器械的相关法律法规，保证产品来源合法且符合国家相关法律法规规定，保证产品储运要求及产品质量。甲方保证货物附带随货通行单并盖出库专用章，且内容格式符合法规要求。\n" +
                    "      </p>\n" +
                    "      <p>（2）乙方质量责任</p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        乙方收货后负责货物验收。如有产品错误发货、明显损坏、货物清单与实物不符等问题，乙方应在收到货物的24小时内书面通知甲方并按甲方要求提供相应问题的证明文件，逾期视同验收合格。经甲方合适确认后，乙方按照甲方要求退回相关产品，所有退回产品由乙方提前支付保险和运输费用并用原始包装妥善包装。\n" +
                    "      </p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        乙方保证产品可追溯，依照法规要求留存销售记录、物流记录等，并在接到甲方的产品追溯要求后6小时内，回复产品追溯信息。\n" +
                    "      </p>\n" +
                    "      <p>\n" +
                    "        二、甲乙双方互相提供医疗器械经营符合法律、法规要求的资质文件，并加盖企业公章。\n" +
                    "      </p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        甲方保证提供的医疗器械产品具有医疗器械注册证或备案凭证，产品质量符合产品标准等有关要求，并保证提供的医疗器械产品的产品包装、标签、说明书等符合有关规定。甲乙双方依照法律规范处理产品质量投诉、医疗器械可疑不良事件、产品召回等。\n" +
                    "      </p>\n" +
                    "      <p>三、产品运输的质量保证及责任</p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        甲方负责运输：产品运输过程中发生的产品质量问题，甲方协助乙方进行问题调查。\n" +
                    "      </p>\n" +
                    "      <p style='text-indent: 32px'>\n" +
                    "        乙方自行提货：乙方自行运输或乙方委托承运商运输的，乙方承担产品运输质量责任。\n" +
                    "      </p>\n" +
                    "      <p>\n" +
                    "        四、如双方对医疗器械产品质量产生争议，以法定检验部门的检验结果为准。\n" +
                    "      </p>\n" +
                    "      <p>五、本协议未尽事宜由双方协商解决。</p>\n" +
                    "      <p>六、协议日期：协议有效期限 <input type='text 'id='month' style='width: 10%;'> 个月；自 <input type='text 'id='accreditTime' style='width: 40%;'</p>" +
                    "      <p>本协议一式两份（每份具有同等法律效力，经双方盖章后生效）</p>\n" +
                    "      <p></p>\n" +
                    "      <div\n" +
                    "        style='\n" +
                    "          line-height: 1;\n" +
                    "          font-size: 16px;\n" +
                    "          position: relative;\n" +
                    "          width: 100%;\n" +
                    "          height: auto;\n" +
                    "          overflow: hidden;\n" +
                    "        '\n" +
                    "      >\n" +
                    "        <div style='width: 50%; box-sizing: border-box;float: left;'>\n" +
                    "            <p>\n" + "甲方:" + gfcompany.getCompanyName() +
                    "              </p>\n" +
                    "              <p>盖章：</p>\n" +
                    "              <p>签署日期：：<input type='datetime-local' id='jtime' /></p>\n" +
                    "        </div>\n" +
                    "        <div style='width: 50%; box-sizing: border-box;float: right;'>\n" +
                    "            <p style=''>\n" +
                    "                乙方：\n" + company.getCompanyName() +
                    "              </p>\n" +
                    "              <p style=''>盖章：</p>\n" +
                    "              <p style=''>签署日期：：<input type='datetime-local' id='ytime' /></p>\n" +
                    "        </div>\n" +
                    "      </div>\n" +
                    "    </div>\n" +
                    "\n" +
                    "  </div>";
            String d = a.replaceAll("\\+", "");
            String e = d.replaceAll("\\\\n", "");
            String f = e.replaceAll("\\\\", "");
            resMap.put("Quality", f);
        } else if (type.equals("1")) {
            String a = " <p style='font-size: 22px; font-weight: bold; text-align: center'>\n" +
                    "      法人授权委托书\n" +
                    "    </p>\n" +
                    "    <p style='font-size: 16px; line-height: 1.5; text-indent: 32px'>\n" +
                    "      兹由" + gfcompany.getCompanyName() + " \n" +
                    "      法人代表" + gfcompany.getCorporateRepresentative() + "授权\n" + companyOther.getUserName() + "先生" + "（身份证号：" + companyOther.getIdcard() + "）" +
                    "      <br/>联系电话：\n" + companyOther.getPhone() + "&nbsp;&nbsp;&nbsp;&nbsp;邮箱:" + companyOther.getEmail() + "&nbsp;&nbsp;&nbsp;&nbsp;负责我司与" + company.getCompanyName() +
                    "      一切销售业务事宜。<br/>具体授权如下：\n" +
                    "    </p>\n" +
                    "    <p style='text-indent: 32px; line-height: 2; font-size: 16px'>\n" +
                    "      1.授权销售品种: <textarea style='width: 50%; height: 30%;'id='accreditVariety'>" +
                    "</textarea>" +
                    "    </p>\n" +
                    "    <p style='text-indent: 32px; line-height: 2; font-size: 16px'>\n" +
                    "      2.授权销售地域： <textarea style='width: 50%; height: 30%;' id='accreditRegional'>" +
                    "</textarea>" +
                    "    </p>\n" +
                    "    <p style='text-indent: 32px; line-height: 2; font-size: 16px'>\n" +
                    "      3. 授权期限： <textarea style='width: 50%; height: 30%; 'id='accreditTime'>" +
                    "</textarea>" +
                    "    </p>\n" +
                    "    <div style='display: flex; justify-content: space-between'>\n" +
                    "      <img src='" + companyOther.getIdcardzmPhoto() + "' alt='' style='width: 45%; height: auto' id='sfzz' />\n" +
                    "      <img src='" + companyOther.getIdcardfmPhoto() + "' alt='' style='width: 45%; height: auto' id='sfzf' />\n" +
                    "    </div>\n" +
                    "\n" +
                    "    <div\n" +
                    "      style='\n" +
                    "        line-height: 2;\n" +
                    "        font-size: 16;\n" +
                    "        position: relative;\n" +
                    "        width: 40%;\n" +
                    "      position:' relative;right: 0;'" +
                    "      '\n" +
                    "    >\n" +
                    "      <p style=''>" + gfcompany.getCompanyName() + "</p>\n" +
                    "      <p style=''>授权人（签章）：</p>\n <p style=''>签署日期：：<input type='datetime-local' id='ytime' /></p>" +
                    "      <p style=''></p>\n" +
                    "    </div>";

            String d = a.replaceAll("\\+", "");
            String e = d.replaceAll("\\\\n", "");
            String f = e.replaceAll("\\\\", "");
            resMap.put("Quality", f);
        } else if (type.equals("2")) {

            String a =
                    "<div style=\"font-size: 16px; line-height: 2.5;\">\n" +
                    "    <div style=\"font-size: 24px; font-weight: bold; text-align: center;\">医疗器械产品销售授权书</div>\n" +
                    "    <div style=\"text-indent: 2em\">授权编号：<input id=\"sqbh\" type=\"text\"></div>\n" +
                    "    <div style=\"text-indent: 2em\">授权日期：<input id=\"ytime\" type=\"date\"></div>\n" +
                    "    <div style=\"text-indent: 2em\">致：<input type='input' id='z' /></div>\n" +
                    "    <div style=\"text-indent: 2em\">"+gfcompany.getCompanyName()+" 授权 "+ company.getCompanyName() +" 为我司经销商，负责我司产品 <input id=\"productName\" type=\"text\"> 在贵单位的销售及招投标公司，并全权处理相关事宜。</div>\n" +
                    "    <div style=\"text-indent: 2em\">授权期限：<input id=\"sqqxStart\" type=\"date\"> / <input id=\"sqqxEnd\" type=\"date\"></div>\n" +
                    "    <div style=\"text-indent: 2em\">在授权期限内上述经销关系发生任何变更，本公司将给予相应书面通知。自授 权之日起三个月内，若" + company.getCompanyName()+ "与本公司没有业务往来，本授权自动作废。</div>\n" +
                    "    <div style=\"text-align: right;\">" + gfcompany.getCompanyName() +"</div>\n" +
                    "</div>";
            String d = a.replaceAll("\\+", "");
            String e = d.replaceAll("\\\\n", "");
            String f = e.replaceAll("\\\\", "");
            resMap.put("Quality", f);
        }

        return resMap;
    }

    @Override
    public void insertQuality(CompanyAudit companyAudit) {
        CompanyAudit company = companyMapper.selectComapnyAudit(companyAudit);
        if (company == null) {
            companyMapper.insertQuality(companyAudit);

        } else {
            companyMapper.updateQuality(companyAudit);
        }

    }

    @Override
    public void insertLegal(CompanyAudit companyAudit) {

        CompanyAudit company = companyMapper.selectComapnyAudit(companyAudit);

        if (company == null) {
            companyMapper.insertLegal(companyAudit);

        } else {
            companyMapper.updateLegal(companyAudit);
        }
    }

    @Override
    public void insertsaleAudit(CompanyAudit companyAudit) {

        CompanyAudit company = companyMapper.selectComapnyAudit(companyAudit);

        if (company == null) {
            companyMapper.insertsaleAudit(companyAudit);

        } else {
            companyMapper.updatesaleAudit(companyAudit);
        }
    }

    @Override
    public void Quality(CompanyAudit companyAudit) {
        String time = "";
        if (companyAudit.getWrtiteTime() != null) {
            time = companyAudit.getWrtiteTime().substring(0, 10);
        }
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        Company company = companyMapper.selectCompany(companyAudit.getCompanyId());

        Company gfcompany = companyMapper.selectCompany(sysUser.getDeptId());

        String fileName = company.getCompanyName() + "质量保证和售后服务协议" + ".pdf";
        String downloadPath = RuoYiConfig.getDownloadPath();

        File d = new File(downloadPath);
        if (!d.exists()) {
            d.mkdir();
        }
        File file = new File(downloadPath + "/QualityPdf");
        if (!file.exists()) {
            file.mkdir();
        }
        String destPath = downloadPath + "QualityPdf/" + fileName;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destPath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        StringBuilder str = new StringBuilder();
        str.append("<!DOCTYPE html>");
        str.append("<html lang=\"zh\">");
        str.append("  <head>\n" +
                "    <meta charset=\"UTF-8\" />\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n" +
                "    <title>Document</title>\n" +
                "  </head>\n" +
                "  <body style=\"font-size: 16px;font-family:SimSun;\">");
//                "<body style=\"font-family:SimSun;\">");

        str.append("<div>\n" +
                "    <p style=\"font-size: 22px; font-weight: bold; text-align: center\">\n" +
                "      质量保证和售后服务协议\n" +
                "    </p>\n" +
                "    <p style=\"line-height: 1; font-size: 16px\">\n" +
                "      甲方（供货方）：<span style=\"text-decoration: underline\"\n" +
                "        >" + gfcompany.getCompanyName() + "</span\n" +
                "      >\n" +
                "    </p>\n" +
                "    <p style=\"line-height: 1; font-size: 16px\">\n" +
                "      乙方（购货方）:<span style=\"text-decoration: underline\"\n" +
                "        >" + company.getCompanyName() + "</span\n" +
                "      >\n" +
                "    </p>\n" +
                "    <p style=\"font-size: 16px; line-height: 1; text-indent: 32px\">" +
                "   为了严格执行《医疗器械监督管理条例》及国家有关法律、法规的要求，加强医疗器械质量管理，确保医疗器械质量，明确双方质量责任，签订以下质量保证协议：" + " </p>" +
                "    <div style=\"font-size: 16px; line-height: 1\">\n" +
                "      <p>一、双方质量责任</p>\n" +
                "      <p>（1）甲方质量责任</p>" +
                "      <p style=\"text-indent: 32px\">" +
                "  甲方应遵守国家有关医疗器械的相关法律法规，保证产品来源合法且符合国家相关法律法规规定，保证产品储运要求及产品质量。甲方保证货物附带随货通行单并盖出库专用章，且内容格式符合法规要求。" + "</p>" +
                "      <p>（2）乙方质量责任</p>" +
                "      <p style=\"text-indent: 32px\">" +
                "        乙方收货后负责货物验收。如有产品错误发货、明显损坏、货物清单与实物不符等问题，乙方应在收到货物的24小时内书面通知甲方并按甲方要求提供相应问题的证明文件，逾期视同验收合格。经甲方合适确认后，乙方按照甲方要求退回相关产品，所有退回产品由乙方提前支付保险和运输费用并用原始包装妥善包装。\n" +
                "      </p>" +
                "      <p style=\"text-indent: 32px\">" +
                "        乙方保证产品可追溯，依照法规要求留存销售记录、物流记录等，并在接到甲方的产品追溯要求后6小时内，回复产品追溯信息。\n" +
                "      </p>\n" +
                "      <p>\n" +
                "        二、甲乙双方互相提供医疗器械经营符合法律、法规要求的资质文件，并加盖企业公章。\n" +
                "      </p>\n" +
                "      <p style=\"text-indent: 32px\">\n" +
                "        甲方保证提供的医疗器械产品具有医疗器械注册证或备案凭证，产品质量符合产品标准等有关要求，并保证提供的医疗器械产品的产品包装、标签、说明书等符合有关规定。甲乙双方依照法律规范处理产品质量投诉、医疗器械可疑不良事件、产品召回等。\n" +
                "      </p>\n" +
                "      <p>三、产品运输的质量保证及责任</p>\n" +
                "      <p style=\"text-indent: 32px\">\n" +
                "        甲方负责运输：产品运输过程中发生的产品质量问题，甲方协助乙方进行问题调查。\n" +
                "      </p>\n" +
                "      <p style=\"text-indent: 32px\">\n" +
                "        乙方自行提货：乙方自行运输或乙方委托承运商运输的，乙方承担产品运输质量责任。\n" +
                "      </p>\n" +
                "      <p>\n" +
                "        四、如双方对医疗器械产品质量产生争议，以法定检验部门的检验结果为准。\n" +
                "      </p>\n" +
                "      <p>五、本协议未尽事宜由双方协商解决。</p>\n" +
                "      <p>六、协议日期：协议有效期限" + companyAudit.getYxTime() + "个月；自" + companyAudit.getAccreditTime() + "</p>\n" +
                "      <p>本协议一式两份（每份具有同等法律效力，经双方盖章后生效）</p>\n" +
                "      <p></p>\n" +
                "      <div\n" +
                "        style=\"\n" +
                "          line-height: 1;\n" +
                "          font-size: 16px;\n" +
                "          position: relative;\n" +
                "          width: 100%;\n" +
                "          height: auto;\n" +
                "          overflow: hidden;\n" +
                "        \"\n" +
                "      >\n" +
                "        <div style=\"width: 50%; box-sizing: border-box;float: left;\">\n" +
                "            <p>\n" +
                "                甲方：" + gfcompany.getCompanyName() + "\n" +
                "              </p>\n" +
                "              <p>盖章：</p>\n" +
                "              <p>签署日期：" + time + "</p>\n" +
                "        </div>\n" +
                "        <div style=\"width: 50%; box-sizing: border-box;float: right;\">\n" +
                "            <p style=\"\">\n" +
                "                乙方：\n" + company.getCompanyName() +
                "              </p>\n" +
                "              <p style=\"\">盖章：</p>\n" +
                "              <p style=\"\">签署日期：" + time + "</p>\n" +
                "        </div>\n" +

                "      </div>\n" +
                "    </div>\n" +
                "  </div>\n" +
                "  </body>\n" +
                "</html>\n");


        HtmlToPdf.createPdfByHtml(fileOutputStream, str.toString());

        String downloadPath1 = RuoYiConfig.getDownloadPath();
        File file1 = new File(downloadPath1);
        if (!file1.exists()) {
            file1.mkdir();
        }

        String uploadPath = RuoYiConfig.getUploadPath();

        int sbsoluteY = 80;
        String purImgPath = "";

        String fileStr = downloadPath1 + "QualityPdf/" + fileName;
        String fileStr2 = downloadPath1 + "QualityPdf/" + gfcompany.getCompanyName() + "授权" + fileName;
        if (gfcompany.getElectronicSealUrl() != null) {
            String purUrl = gfcompany.getElectronicSealUrl();
            String[] split1 = purUrl.split("/profile/upload");
            purImgPath = uploadPath + split1[1];

            try {
                ImgToPdf.imgToPdfLeft(fileStr, fileStr2, purImgPath, sbsoluteY);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            companyAudit.setAuditcompanyId(sysUser.getDeptId());

            companyAudit.setQuality("/QualityPdf/" + gfcompany.getCompanyName() + "授权" + fileName);

            insertQuality(companyAudit);
        }

    }

    /**
     * 查询用户信息
     *
     * @param map 查询条件
     * @return 结果
     */
    @Override
    public List<SysUser> selectUserAndDept(Map map) {
        return companyMapper.selectUserAndDept(map);
    }

    /**
     * 通过公司的统一信用代码查询
     *
     * @param socialCreditCode 公司的统一代码
     * @return 结果
     */
    @Override
    public Company selectBySocialCreditCode(String socialCreditCode) {
        return companyMapper.selectBySocialCreditCode(socialCreditCode);
    }


}
